package com.warmlight.voicepacket.ui.user;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.dbdata.DBFloatPlayListDetail;
import com.warmlight.voicepacket.dbdata.DBFloatPlaylist;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDaoHelp;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDetailDaoHelp;
import com.warmlight.voicepacket.http.Callback;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.KeyboardUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.StringUtils;
import com.warmlight.voicepacket.utils.WaveHeader;
import com.warmlight.voicepacket.web.WebViewActivity;
import com.warmlight.voicepacket.widget.AutoLinkStyleTextView;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

public class LoginForgetPassWordActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_phone_num;
    private EditText et_code;
    private TextView tv_get_code;
    private EditText et_password;
    private Button bt_regist;
    private AutoLinkStyleTextView tv_nc;
    private RelativeLayout rl_all;
    private String phone;
    private CountDownTimer mytime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            if (bundle.containsKey("phone")){
                phone = bundle.getString("phone");
            }
        }
        initView();
        initListener();
        initData();
    }

    private void initData() {
        if (!TextUtils.isEmpty(phone)){
            et_phone_num.setText(phone);
        }
    }


    private void initListener() {
        tv_get_code.setOnClickListener(this);
        bt_regist.setOnClickListener(this);
        tv_nc.setOnClickCallBack(new AutoLinkStyleTextView.ClickCallBack() {
            @Override
            public void onClick(int position) {
                if (0==position){
                    WebViewActivity.loadUrl(getContext(),HttpConfig.USERCONDINTION,"用户使用条款");
                }else if (1==position){
                    WebViewActivity.loadUrl(getContext(),HttpConfig.USERPRIVACY,"隐私策略");
                }
            }
        });
        rl_all.setOnClickListener(this);
        et_phone_num.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    //埋点
                    MobclickAgent.onEvent(getContext(), MobClickHelper.FORGET_PHONE);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                    ZhugeSDK.getInstance().track(getContext(), MobClickHelper.FORGET_PHONE);
                }
            }
        });
        et_code.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    //埋点
                    MobclickAgent.onEvent(getContext(), MobClickHelper.FORGET_CAPTCHA);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                    ZhugeSDK.getInstance().track(getContext(), MobClickHelper.FORGET_CAPTCHA);
                }
            }
        });
        et_password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus){
                    //埋点
                    MobclickAgent.onEvent(getContext(), MobClickHelper.FORGET_PASS);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                    ZhugeSDK.getInstance().track(getContext(), MobClickHelper.FORGET_PASS);
                }
            }
        });
        et_phone_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    private void textChanged(){
        String phone = et_phone_num.getText().toString().trim();
        String password = et_password.getText().toString().trim();
        String code = et_code.getText().toString().trim();
        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(password) || TextUtils.isEmpty(code)){
            bt_regist.setEnabled(false);
        }else{
            if (password.length()<6){
                bt_regist.setEnabled(false);
            }else {
                bt_regist.setEnabled(true);
            }
        }
    }

    private void initView() {
        setTitle("忘记密码");
        setBack();
        et_phone_num = (EditText) findViewById(R.id.et_phone_num);
        et_code = (EditText) findViewById(R.id.et_code);
        tv_get_code = (TextView) findViewById(R.id.tv_get_code);
        et_password = (EditText) findViewById(R.id.et_password);
        bt_regist = (Button) findViewById(R.id.bt_regist);
        bt_regist.setEnabled(false);
        tv_nc = (AutoLinkStyleTextView) findViewById(R.id.tv_nc);
        rl_all = (RelativeLayout) findViewById(R.id.rl_all);
    }

    @Override
    public void backClick() {
        super.backClick();
        //埋点
        MobclickAgent.onEvent(getContext(), MobClickHelper.FORGET_BACK);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
        ZhugeSDK.getInstance().track(getContext(), MobClickHelper.FORGET_BACK);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        //埋点
        MobclickAgent.onEvent(getContext(), MobClickHelper.FORGET_BACK);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
        ZhugeSDK.getInstance().track(getContext(), MobClickHelper.FORGET_BACK);
    }

    private void getCode(){
        String phoneNum = et_phone_num.getText().toString();
        if (TextUtils.isEmpty(phoneNum)){
            showToast("请先输入手机号");
            return;
        }
        if (!StringUtils.isPhoneNumValid(phoneNum)){
            showToast("手机号错误请重新输入");
            return;
        }
//        tv_get_code.setText("发送短信中");
        startTimer(tv_get_code,"获取验证码",100,1);
        String url = HttpConfig.MSG_CODE;
        TreeMap<String,String> map = new TreeMap<>();
        map.put("mobile",phoneNum);
        map.put("type","2");
        HttpClient.post(url, map, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mytime != null){
                            mytime.cancel();
                        }
                        showToast("短信发送失败，请稍后重试");
                        tv_get_code.setText("获取验证码");
                    }
                });
            }

            @Override
            public void onResponse(Call call, String response)   {
//                String string = response.body().string();
                ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                if (listMapByJson.size()>0){
                    final Map<String, String> map1 = listMapByJson.get(0);
                    if (TextUtils.equals("200",map1.get("code"))){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showToast("验证码已发送");
//                                startTimer(tv_get_code,"获取验证码",100,1);
                            }
                        });

                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mytime != null){
                                    mytime.cancel();
                                }
                                showToast(map1.get("msg"));
                                tv_get_code.setText("获取验证码");
//                                if (TextUtils.equals("201",map1.get("code"))){
//                                    showLoginDialog();
//                                }
                            }
                        });
                    }
                }
            }
        });
    }

    private void showLoginDialog(){
        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                .setTitle("该手机号已注册")
                .setMessage("是否以用该手机号登录账号")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("去登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Intent intent = new Intent(getContext(),AccountLoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }).create();
        alertDialog.show();
    }

    /**
     * 在按钮上启动一个定时器
     * @param tvVerifyCode 验证码控件
     * @param defaultString 按钮上默认的字符串
     * @param max 失效时间（单位：s）
     * @param interval 更新间隔（单位：s）
     * */
    public void startTimer(final TextView tvVerifyCode,
                           final String defaultString,
                           int max,
                           int interval)
    {
//        tvVerifyCode.setEnabled(false);

        // 由于CountDownTimer并不是准确计时，在onTick方法调用的时候，time会有1-10ms左右的误差，这会导致最后一秒不会调用onTick()
        // 因此，设置间隔的时候，默认减去了10ms，从而减去误差。
        // 经过以上的微调，最后一秒的显示时间会由于10ms延迟的积累，导致显示时间比1s长max*10ms的时间，其他时间的显示正常,总时间正常
        // 第一次调用会有1-10ms的误差，因此需要+15ms，防止第一个数不显示，第二个数显示2s
        mytime = new CountDownTimer(max * 1000, interval * 1000 - 10) {

            @Override
            public void onTick(long time) {
                // 第一次调用会有1-10ms的误差，因此需要+15ms，防止第一个数不显示，第二个数显示2s
                if(null == tvVerifyCode)
                    this.cancel();
                else
                    tvVerifyCode.setText("" + ((time + 15) / 1000) + "s");
            }

            @Override
            public void onFinish() {
                if(null == tvVerifyCode) {
                    this.cancel();
                    return;
                }
                tvVerifyCode.setEnabled(true);
                tvVerifyCode.setText(defaultString);

            }
        }.start();
    }

    private void regist(){
        final String phoneNum = et_phone_num.getText().toString();
        if (TextUtils.isEmpty(phoneNum)){
            showToast("请先输入手机号");
            return;
        }
        if (!StringUtils.isPhoneNumValid(phoneNum)){
            showToast("手机号错误请重新输入");
            return;
        }
        String etCode = et_code.getText().toString().trim();
        if (TextUtils.isEmpty(etCode)){
            showToast("请输入验证码");
            return;
        }
        String password = et_password.getText().toString();
        if (TextUtils.isEmpty(password)){
            showToast("请输入密码");
            return;
        }
        if (!StringUtils.isPasswordValid(password)){
            showToast("密码6-12位");
            return;
        }
        String url = HttpConfig.FORGET_PASSWORD;
        final TreeMap<String,String> map = new TreeMap<>();
        map.put("mobile",phoneNum);
        map.put("sms_code",etCode);
        map.put("password",password);
        HttpClient.post(url, map, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showToast("登录失败，请稍后再试");
                    }
                });
            }

            @Override
            public void onResponse(Call call, String response)   {
//                String string = response.body().string();
                ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                if (listMapByJson.size()>0){
                    final Map<String, String> map1 = listMapByJson.get(0);
                    if (TextUtils.equals("200",map1.get("code"))){
//                        String data = map1.get("data");//只有code
//                        ArrayList<Map<String, String>> dataList = JSONUtils.getListMapByJson(data);
//                        Map<String, String> map2 = dataList.get(0);
//                        String auth_key = map2.get("auth_key");
//                        String uid = map2.get("uid");
//                        String last_login = map2.get("last_login");
//
//                        SPUtils.login(auth_key,uid);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //登录成功后到晚上个人资料页面
                                showToast("修改成功，请重新登录");
                                Intent intent = new Intent();
                                intent.putExtra("phone",phoneNum);
                                setResult(200,intent);
                                goLoginEditUserInforActivity();
                            }
                        });

                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //登录成功后到晚上个人资料页面
                                showToast(map1.get("msg"));
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * 去到完善个人资料页面
     */
    private void goLoginEditUserInforActivity(){
//        Intent intent = new Intent(getContext(),LoginEditUserInfoActivity.class);
//        startActivity(intent);
//        EventBus.getDefault().post(new Login(true));
        finish();
//        loginSuccess();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_get_code:
                //埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.FORGET_CAPTCHA_CLICK);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.FORGET_CAPTCHA_CLICK);
                String text = tv_get_code.getText().toString();
                if (TextUtils.equals("获取验证码",text)) {
                    getCode();
                }
                break;
            case R.id.bt_regist:
                //埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.FORGET_OK);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.FORGET_OK);
                regist();
                break;
            case R.id.rl_all:
                KeyboardUtils.hideInputMethod(getContext());
                break;
        }
    }
    private void checkMadeSelf(){
        final ProgressDialog dd = new ProgressDialog(getContext());
        dd.setMessage("正在检测数据，请勿关闭应用");
        dd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dd.setCanceledOnTouchOutside(false);
        dd.setCancelable(false);
        dd.show();

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                final List<DBFloatPlaylist> dbFloatPlaylists = DBFloatPlayListDaoHelp.loadAll(getContext());
                if (dbFloatPlaylists.size()>0){
                    boolean isHasMadeSelf = false;
                    boolean isHasAudio = false;
                    for (int i = 0;i<dbFloatPlaylists.size();i++){
                        DBFloatPlaylist dbFloatPlaylist = dbFloatPlaylists.get(i);
                        if (!TextUtils.isEmpty(dbFloatPlaylist.getList_audio())){
                            String list_audio = dbFloatPlaylist.getList_audio();
                            //这里要注意，当list_audio是""时，split有值，就是""；所以加一个判断
                            if (TextUtils.isEmpty(list_audio)){
                                continue;
                            }else {
                                isHasAudio = true;
                            }
                            String[] split = list_audio.split(",");
                            List<String> strings = Arrays.asList(split);
                            for(String s:strings){
                                DBFloatPlayListDetail detail = DBFloatPlayListDetailDaoHelp.queryBuilderbyaudioid(getContext(), s);
                                if (!detail.getAudio_url().contains("http")){
                                    isHasMadeSelf = true;
                                    break;
                                }
                            }
                            if (isHasMadeSelf) {
                                break;
                            }
                        }

                    }
                    if (isHasAudio){
                        if (isHasMadeSelf){
                            emitter.onNext("1");
                            emitter.onComplete();
                        }else{
                            emitter.onNext("0");
                            emitter.onComplete();
                        }
                    }else{
                        emitter.onNext("2");//无数据
                        emitter.onComplete();
                    }



                }else{
                    emitter.onNext("-1");
                    emitter.onComplete();
                }

            }
        }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String o) {
                        if (TextUtils.equals("1",o)){
                            showTongbuDialog(true);

                        }else if (TextUtils.equals("0",o)){

                            showTongbuDialog(false);
                        }else if (TextUtils.equals("-1",o)){
                            DBFloatPlayListDetailDaoHelp.clear(getContext());
                            EventBus.getDefault().post(new Login(true));
                            getContext().finish();
                        }else if (TextUtils.equals("2",o)){
                            DBFloatPlayListDetailDaoHelp.clear(getContext());
                            EventBus.getDefault().post(new Login(true));
                            getContext().finish();
                        }
                        dd.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void showTongbuDialog(final boolean isHasMadeSelf){
        final List<DBFloatPlaylist> dbFloatPlaylists = DBFloatPlayListDaoHelp.loadAll(getContext());
        AlertDialog dialog = new AlertDialog.Builder(getContext())
                .setTitle("是否同步本地数据")
                .setMessage("检测到该设备未登录时本地存有数据，是否" +
                        "同步之前数据到此登录的账号中，同步后数据会绑定到账号中且之前的数据会被清除并无法找回")
                .setCancelable(false)
                .setNegativeButton("同步", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (isHasMadeSelf){
                            showMadeSelfDialog(dbFloatPlaylists);
                        }else {
                            tongbuData(dbFloatPlaylists);
                        }
                        dialog.dismiss();
                        //埋点
                        MobclickAgent.onEvent(getContext(), MobClickHelper.UPLOADWARM_YES);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                        ZhugeSDK.getInstance().track(getContext(), MobClickHelper.UPLOADWARM_YES);
                    }
                }).setPositiveButton("不同步", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //埋点
                        MobclickAgent.onEvent(getContext(), MobClickHelper.UPLOADWARM_NO);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                        ZhugeSDK.getInstance().track(getContext(), MobClickHelper.UPLOADWARM_NO);
                        EventBus.getDefault().post(new Login(true));
                        dialog.dismiss();
                        getContext().finish();
                    }
                }).create();

        dialog.show();
    }

    private void loginSuccess(){
        checkMadeSelf();
//        final ProgressDialog dd = new ProgressDialog(getContext());
//        dd.setMessage("正在检测数据，请勿关闭应用");
//        dd.setCanceledOnTouchOutside(false);
//        dd.setCancelable(false);
//        dd.show();
//        final List<DBFloatPlaylist> dbFloatPlaylists = DBFloatPlayListDaoHelp.loadAll(getContext());
//        if (dbFloatPlaylists.size()>0){
//            boolean isHasMadeSelf = false;
//            for (int i = 0;i<dbFloatPlaylists.size();i++){
//
//                DBFloatPlaylist dbFloatPlaylist = dbFloatPlaylists.get(i);
//                if (!TextUtils.isEmpty(dbFloatPlaylist.getList_audio())){
//                    String list_audio = dbFloatPlaylist.getList_audio();
//                    String[] split = list_audio.split(",");
//                    List<String> strings = Arrays.asList(split);
//                    for(String s:strings){
//                        DBFloatPlayListDetail detail = DBFloatPlayListDetailDaoHelp.queryBuilderbyaudioid(getContext(), s);
//                        if (!detail.getAudio_url().contains("http")){
//                            isHasMadeSelf = true;
//                            break;
//                        }
//                    }
//                    if (isHasMadeSelf) {
//                        break;
//                    }
//                }
//
//            }
//
//            dd.dismiss();
////            if (!isShow){
////                EventBus.getDefault().post(new Login(true));
////                getContext().finish();
////                return;
////            }
//            final boolean finalIsHasMadeSelf = isHasMadeSelf;
//            AlertDialog dialog = new AlertDialog.Builder(getContext())
//                    .setTitle("是否同步本地数据")
//                    .setMessage("检测到该设备未登录时本地存有数据，是否" +
//                            "同步之前数据到此登录的账号中，同步后数据会绑定到账号中且之前的数据会被清除并无法找回")
//                    .setCancelable(false)
//                    .setNegativeButton("同步", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            if (finalIsHasMadeSelf){
//                                showMadeSelfDialog(dbFloatPlaylists);
//                            }else {
//                                tongbuData(dbFloatPlaylists);
//                            }
//                            dialog.dismiss();
//                            //埋点
//                            MobclickAgent.onEvent(getContext(), MobClickHelper.UPLOADWARM_YES);
////                HashMap<String, Object> temp = new HashMap<>();
////                temp.put("登录返回", "");
//                            ZhugeSDK.getInstance().track(getContext(), MobClickHelper.UPLOADWARM_YES);
//                        }
//                    }).setPositiveButton("不同步", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            //埋点
//                            MobclickAgent.onEvent(getContext(), MobClickHelper.UPLOADWARM_NO);
////                HashMap<String, Object> temp = new HashMap<>();
////                temp.put("登录返回", "");
//                            ZhugeSDK.getInstance().track(getContext(), MobClickHelper.UPLOADWARM_NO);
//                            EventBus.getDefault().post(new Login(true));
//                            dialog.dismiss();
//                            getContext().finish();
//                        }
//                    }).create();
//
//            dialog.show();
//
//        }else{
//            dd.dismiss();
//            EventBus.getDefault().post(new Login(true));
//            getContext().finish();
//        }
    }

    private void showMadeSelfDialog(final List<DBFloatPlaylist> dbFloatPlaylists){
        AlertDialog dialog = new AlertDialog.Builder(getContext())
                .setTitle("自制内容需审核")
                .setMessage("检测到您同步上传的数据中有自制内容，" +
                        "我们会对其审核，若审核未通过则该内容不会上传同步到该账号，请知悉")
                .setCancelable(false)
                .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //埋点
                        MobclickAgent.onEvent(getContext(), MobClickHelper.EXAM_YES);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                        ZhugeSDK.getInstance().track(getContext(), MobClickHelper.EXAM_YES);
                        tongbuData(dbFloatPlaylists);
                        dialog.dismiss();
                    }
                }).create();

        dialog.show();
    }

    @SuppressLint("CheckResult")
    private void tongbuData(final List<DBFloatPlaylist> dbFloatPlaylists){
        final ProgressDialog dialog = new ProgressDialog(getContext());
//        dialog.setTitle("数据同步中");
        dialog.setMessage("正在同步数据，请勿关闭应用");
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setCancelable(false);
        dialog.show();



        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                int suc = 0;
                int fail = 0;
                int all = 0;
                for (int i=0;i<dbFloatPlaylists.size();i++){
                    DBFloatPlaylist dbFloatPlaylist = dbFloatPlaylists.get(i);
                    String list_audio = dbFloatPlaylist.getList_audio();
                    if (!TextUtils.isEmpty(list_audio)){
                        all++;
                        boolean isSuc = tongbu(dbFloatPlaylist);
                        if (isSuc){
                            suc++;
                        }else{
                            fail++;
                        }
                    }
                }
                Map<String,String> map = new HashMap<>();
                map.put("suc",suc+"");
                map.put("fail",fail+"");
                map.put("all",all+"");
                emitter.onNext(map);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                if (dialog != null){
                    dialog.dismiss();
                }
                EventBus.getDefault().post(new Login(true));
//                DBFloatPlayListDetailDaoHelp.clear(getContext());
                Map<String,String> map = (Map<String, String>) o;
                String suc = map.get("suc");
                String fail = map.get("fail");
                String all = map.get("all");
                if (TextUtils.equals(suc,all)){
                    DBFloatPlayListDetailDaoHelp.clear(getContext());
                }
                showToast("共上传播单"+all+"个，成功"+suc+"个，失败"+fail+"个");
                getContext().finish();
                //todo
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                if (dialog != null){
                    dialog.dismiss();
                }
            }
        });


    }
    private OSS mOss;
    private OSS getOSS(){
        if (mOss == null) {
            String endpoint = HttpConfig.endpoint;
            String stsServer = "STS应用服务器地址，例如http://abc.com";
//推荐使用OSSAuthCredentialsProvider。token过期可以及时更新
            OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(HttpConfig.accessKeyId, HttpConfig.accessKeySecret);
//该配置类如果不设置，会有默认配置，具体可看该类
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            mOss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
        }
        return mOss;
    }
    //数据格式： [{"id";"线上音频id"},{"title":"本地音频title","url":"url","duration":"微秒","cover_name":"播单名称"} ]
    private boolean tongbu(DBFloatPlaylist dbFloatPlaylist){
        List<String> strings = new ArrayList<>();
        String list_audio = dbFloatPlaylist.getList_audio();
        if (!TextUtils.isEmpty(list_audio)){
            String[] split = list_audio.split(",");
//            List<String> strings = Arrays.asList(split);
            for (int i=0;i<split.length;i++){
                strings.add(split[i]);
            }
        }
        ArrayList<DBFloatPlayListDetail> dbFloatPlayListDetails = new ArrayList<>();
        for (int i=0;i<strings.size();i++) {
            String s = strings.get(i);
            DBFloatPlayListDetail detail = DBFloatPlayListDetailDaoHelp.queryBuilderbyaudioid(getContext(), s);
            if (!detail.getAudio_url().contains("http")){
                String localFile = detail.getAudio_url();
                File file = new File(localFile);
                if (file.exists()) {
                    dbFloatPlayListDetails.add(detail);
                }else{
                    strings.remove(i);
                    i--;
                }
            }
        }

        int size = 0;
        for (int i=0;i<dbFloatPlayListDetails.size();i++){
            OSS oss = getOSS();
            DBFloatPlayListDetail detail = dbFloatPlayListDetails.get(i);
            String localFile = detail.getAudio_url();
            File file = new File(localFile);
            if (!file.exists()) {
//                Log.w("AsyncPutImage", "FileNotExist");
//                Log.w("LocalFile", localFile);
                continue;
            }
            if (file.getName().contains(".pcm")){
                File file1 = new File(file.getParent(),file.getName().replace(".pcm",".wav"));
                startPcmToWav(file.getAbsolutePath(),file1.getAbsolutePath());
                file = file1;
            }

            String object = HttpConfig.localAudio() + file.getName();
            if (object.equals("")) {
//                Log.w("AsyncPutImage", "ObjectNull");
                continue;
            }




            // 构造上传请求
            PutObjectRequest put = new PutObjectRequest(HttpConfig.bucket, object, file.getAbsolutePath());
// 文件元信息的设置是可选的
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentType("application/octet-stream"); // 设置content-type
// metadata.setContentMD5(BinaryUtil.calculateBase64Md5(uploadFilePath)); // 校验MD5
// put.setMetadata(metadata);
            try {
                PutObjectResult putResult = oss.putObject(put);
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", putResult.getETag());
                Log.d("RequestId", putResult.getRequestId());
                detail.setAudio_ps(HttpConfig.ali+object);
                size ++;
            } catch (ClientException e) {
                // 本地异常如网络异常等
                e.printStackTrace();
                detail.setAudio_ps("");
            } catch (ServiceException e) {
                // 服务异常
                Log.e("RequestId", e.getRequestId());
                Log.e("ErrorCode", e.getErrorCode());
                Log.e("HostId", e.getHostId());
                Log.e("RawMessage", e.getRawMessage());
                detail.setAudio_ps("");
            }

        }
        if (size == dbFloatPlayListDetails.size()) {
            if (strings.size() > 0) {
                String json = toJson(strings, dbFloatPlayListDetails);
                if (TextUtils.equals("[]", json)) {
                    json = "[{}]";
                }

                String list_name = dbFloatPlaylist.getList_name();
                String url = HttpConfig.SYNC_DATA;
                TreeMap<String, String> treeMap = new TreeMap<>();
                treeMap.put("audio_list", json);
                treeMap.put("member_cover_name", list_name);
                treeMap.put("auth_key", SPUtils.getLoginAuthKey());
                String post = HttpClient.post(url, treeMap);
                if (!TextUtils.isEmpty(post)) {
                    ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(post);
                    if (listMapByJson.size() > 0) {
                        Map<String, String> map = listMapByJson.get(0);
                        if (TextUtils.equals("200", map.get("code"))) {
                            //删除播单内音频数据
                            DBFloatPlayListDaoHelp.deleteAudioId(getContext(), dbFloatPlaylist.getId() + "");
                            return true;
                        } else {

                        }
                    }
                }
            } else {
                //删除播单内音频数据
                DBFloatPlayListDaoHelp.deleteAudioId(getContext(), dbFloatPlaylist.getId() + "");
            }
        }else{

        }
        return false;
    }

    private void startPcmToWav(String src, String target) {
        File file = new File(src);
        if (file != null) {
            try {
                @SuppressWarnings("resource")
                FileInputStream inputStream = new FileInputStream(file);
                // 计算长度
                byte[] buf = new byte[1024 * 100];
                int size = inputStream.read(buf);
                int pcmSize = 0;
                while (size != -1) {
                    pcmSize += size;
                    size = inputStream.read(buf);
                }
                inputStream.close();
                // 填入参数，比特率等。16位双声道，8000HZ
                WaveHeader header = new WaveHeader();
                // 长度字段 = 内容的大小（PCMSize) + 头部字段的大小
                // (不包括前面4字节的标识符RIFF以及fileLength本身的4字节
                header.fileLength = pcmSize + (44 - 8);
                header.FmtHdrLeth = 16;
                header.BitsPerSample = 16;
                header.Channels = 1;
                header.FormatTag = 0x0001;
                header.SamplesPerSec = 8000;
                header.BlockAlign = (short) (header.Channels
                        * header.BitsPerSample / 8);
                header.AvgBytesPerSec = header.BlockAlign
                        * header.SamplesPerSec;
                header.DataHdrLeth = pcmSize;

                byte[] h = header.getHeader();
                assert h.length == 44; // WAV标准，头部应该是44字节

                File targetFile = new File(target);
                if (!targetFile.exists()) {
                    targetFile.createNewFile();
                }
                FileOutputStream outputStream = new FileOutputStream(targetFile);
                inputStream = new FileInputStream(file);
                byte[] buffer = new byte[1024 * 100];
                int tardetSize = inputStream.read(buffer);
                outputStream.write(h, 0, h.length);
                while (tardetSize != -1) {
                    outputStream.write(buffer, 0, tardetSize);
                    tardetSize = inputStream.read(buffer);
                }
                outputStream.close();

//                FileUtils.delete(src);
            } catch (Exception e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        showToast("音频保存失败，请重试");
                    }
                });
            }
        }

    }
    // [{"id";"线上音频id"},{"title":"本地音频title","url":"url","duration":"微秒","cover_name":"播单名称"} ]
    private String toJson(List<String> strings, ArrayList<DBFloatPlayListDetail> dbFloatPlayListDetails){
        JSONArray jsonArray = new JSONArray();
        if (strings.size()==0){

        }else {
            for (String s : strings) {
                DBFloatPlayListDetail detail = DBFloatPlayListDetailDaoHelp.queryBuilderbyaudioid(getContext(), s);
                if (!detail.getAudio_url().contains("http")) {//本地

                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("title", detail.getAudio_title());
                        jsonObject.put("url", getUrl(s, dbFloatPlayListDetails));
                        jsonObject.put("duration", "0");
                        jsonObject.put("cover_name", detail.getAudio_cover_name());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    jsonArray.put(jsonObject);

                } else {//线上
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("id", detail.getAudio_id());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    jsonArray.put(jsonObject);

                }

            }
        }
        return jsonArray.toString();
    }

    private String getUrl(String id,ArrayList<DBFloatPlayListDetail> dbFloatPlayListDetails) {
        for (DBFloatPlayListDetail detail: dbFloatPlayListDetails){
            if (TextUtils.equals(id,detail.getAudio_id())){
                return detail.getAudio_ps();
            }

        }

        return "";
    }


}
